package com.example.wx.service.impl;

import com.example.wx.dao.entity.WxPublicAccountUserDO;
import com.example.wx.dao.entity.WxPublicMainDO;
import com.example.wx.dao.mapper.WxPublicAccountUserMapper;
import com.example.wx.dao.mapper.WxPublicMainMapper;
import com.example.wx.modle.accessToken.Oauth2WebAccessToken;
import com.example.wx.modle.req.WxPublicAuthSuccessReqDTO;
import com.example.wx.other.BizException;
import com.example.wx.service.WxPublicAccountUserService;
import com.example.wx.service.convertor.WxPublicMainConvertor;
import com.example.wx.service.wx.WxService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Objects;


/**
 * 微信公众号-用户-员工绑定关系表
 *
 * @author ZhangBin
 * @date 2025-04-08 09:54:36
 * @Description:
 */
@Slf4j
@Service
public class WxPublicAccountUserServiceImpl implements WxPublicAccountUserService {
    @Autowired
    private WxPublicAccountUserMapper wxPublicAccountUserMapperMapper;
    @Autowired
    private WxPublicMainMapper wxPublicMainMapper;
    @Autowired
    private WxService wxService;


    private static final String LOG_PREFIX = "微信公众号-工号和微信绑定-";


    /**
     * @author: ZhangBin
     * @date: 2025/4/9 10:19
     * @description: 微信网页授权成功绑定用户
     */
    @Override
    public void bind( WxPublicAuthSuccessReqDTO wxPublicAuthSuccessReqDTO) {
        WxPublicMainDO wxPublicMainDO = wxPublicMainMapper.queryObjectByAppId(wxPublicAuthSuccessReqDTO.getAppId());
        if(Objects.isNull(wxPublicMainDO)){
            throw new BizException("获取公众号信息为空");
        }
        Oauth2WebAccessToken oauth2WebAccessToken = wxService.getOauth2WebAccessToken(
                wxPublicMainDO.getWxPublicAppId(),
                wxPublicMainDO.getWxPublicAppSecret(),
                wxPublicAuthSuccessReqDTO.getCode());
        WxPublicAccountUserDO wxPublicAccountUserDO = WxPublicMainConvertor.buildWxPublicAccountUserDO(wxPublicMainDO.getWxPublicAppId(), oauth2WebAccessToken.getOpenid());
        wxPublicAccountUserMapperMapper.save(wxPublicAccountUserDO);
    }
}
